package com.wude.tools;

import com.wude.bean.UserInfo;

import org.xutils.DbManager;
import org.xutils.DbManager.DaoConfig;
import org.xutils.DbManager.DbUpgradeListener;
import org.xutils.ex.DbException;
import org.xutils.x;

public class DbUtils {

    static DbManager.DaoConfig daoConfig;
    private static final int DB_VERSION = 3;

    public static DaoConfig getDaoConfig() {
        if (daoConfig == null) {
            daoConfig = new DbManager.DaoConfig()
                    .setDbName("mengchuang.db")
                    .setDbDir(FileUtils.getDir_de1())
                    .setDbVersion(DB_VERSION)
                    .setAllowTransaction(true)
                    .setDbOpenListener(new DbManager.DbOpenListener() {
                        @Override
                        public void onDbOpened(DbManager db) {
                            // 开启WAL, 对写入加速提升巨大
                            db.getDatabase().enableWriteAheadLogging();
                        }
                    })
                    .setDbUpgradeListener(new DbUpgradeListener() {
                        @Override
                        public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                            if (oldVersion == 3 && newVersion == 4) {
                                updateDB3to4(db);
                            }
                        }
                    });
        }
        return daoConfig;
    }

    private static void updateDB3to4(DbManager db) {
        try {
//            Map<String, String> userinfos = getUserInfoMap(db);
            String table = UserInfo.class.getName();
            String sql = String.format("alter %s add bindphone TEXT", table);
            db.execNonQuery(sql);

        } catch (DbException e) {
            e.printStackTrace();
        }
    }
//
//    private static Map<String, String> getUserInfoMap(DbManager db) throws DbException {
//        db.add
//        Cursor cursor =  db.execQuery("select * from " + UserInfo.class.getName());
//        if (cursor != null) {
//            int count = cursor.getColumnCount();
//            Map<String, String> data = new HashMap<>();
//            if (cursor.moveToFirst()) {
//                cursor.
//            }
//            Field[] fields = UserInfo.class.getDeclaredFields();
//
//        }
//        return null;
//    }

    public static DbManager getDB() {
        return x.getDb(getDaoConfig());
    }
}
